package com.my.demo.oauthService.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import lombok.SneakyThrows;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private DataSource dataSource;

	@Override
	protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
		String usql = "select username,password,isactive as enabled from rbac_user where username=?";
		String asql = "SELECT b.username,c.name AS authority from rbac_user_role a LEFT JOIN rbac_user b ON b.id=a.user_id LEFT JOIN rbac_role c ON a.role_id=c.id WHERE b.username=?";
		authenticationManagerBuilder.jdbcAuthentication().passwordEncoder(passwordEncoder()).dataSource(dataSource)
				.usersByUsernameQuery(usql).authoritiesByUsernameQuery(asql);
	}

	@Bean
	public PasswordEncoder passwordEncoder() {
		return PasswordEncoderFactories.createDelegatingPasswordEncoder();
	}

	@Bean
	@Override
	@SneakyThrows
	public AuthenticationManager authenticationManagerBean() {
		return super.authenticationManagerBean();
	}

	@Override
	@SneakyThrows
	protected void configure(HttpSecurity http) {
		http.requestMatchers().anyRequest().and().authorizeRequests().antMatchers("/oauth/**").permitAll();
	}
}
